package org.example.utils;

import io.lettuce.core.GeoArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.lang.model.type.UnionType;
import java.util.concurrent.TimeUnit;

@Slf4j
public class Redis {
    private StringRedisTemplate redisTemplate;

    private static final String REDIS_SPLIT = ":";
    private static final String REDIS_DEFAULT_PREFIX = "default";

    public Redis(StringRedisTemplate redisTemplate) {
        this.redisTemplate=redisTemplate;
    }
    //获取key
    public String getKey(String key) {
        try{
            return key==null?null:redisTemplate.opsForValue().get(key);
        }catch (Exception e){
            log.error("redis get error, key:{}", key);
            return null;
        }
    }
    //判断key是否存在
    public boolean hasKey(String key) {
        try{
            return key==null?false:redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error("redis has error, key:{}", key);
            return false;
        }
    }
    //设置key
    public boolean setKey(String key, String value) {

        try{
            //.TODO 参数检验
            redisTemplate.opsForValue().set(key,value);
            return true;
        } catch (Exception e) {
            log.error("redis set error, key:{}", key);
            return false;
        }
    }
    //设置过期版本的key和value
    public boolean setKey(String key, String value,long timeOut) {
        log.info("setKey redis对象为:{}", redisTemplate);
        try{
            //.TODO 参数检验
            redisTemplate.opsForValue().set(key,value,timeOut, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            log.error("redis set error, key:{}", key);
            return false;
        }
    }
    public String buildKey(String prefix,String ... args) {
        if(prefix==null){
            prefix=REDIS_DEFAULT_PREFIX;
        }
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(prefix);
        if(args!=null){
            for(String str: args) {
                stringBuilder.append(REDIS_SPLIT).append(str);
            }
        }
        return stringBuilder.toString();
    }
}
